package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.sys.models.bo.SysPermissionSaveBO;
import com.yt.sys.models.dto.SysPermissionDTO;
import com.yt.sys.models.service.ISysPermissionService;
import com.yt.sys.models.vo.SysPermissionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/sysPermission")
@Slf4j
@Api(value = "SysPermissionApiController", tags = "权限信息Api接口")
public class SysPermissionApiController {

    @DubboReference
    private ISysPermissionService sysPermissionService;

    @ApiOperation(value = "新增权限", notes = "新增权限信息（通过YmlConfig生成ID）")
    @PostMapping("/add")
    public Result<SysPermissionVO> add(@RequestBody SysPermissionSaveBO saveBO) {
        // 参数校验
        if (StrUtils.isEmpty(saveBO.getPermissionName()) ||
                StrUtils.isEmpty(saveBO.getPermissionCode()) ||
                saveBO.getType() == null ||
                StrUtils.isEmpty(saveBO.getUrl()) ||
                saveBO.getStatus() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 校验权限编码唯一性
        Wrapper<SysPermissionDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("permission_code", saveBO.getPermissionCode());
        if (sysPermissionService.selectCount(wrapper) > 0) {
            return new Result<>(CodeEnum.FAIL_100010); // 编码重复
        }

        boolean success = sysPermissionService.add(saveBO);
        if (success) {
            SysPermissionDTO dto = sysPermissionService.selectOne(wrapper);
            if (dto == null) {
                return new Result<>(CodeEnum.FAIL_100010);
            }
            SysPermissionVO vo = new SysPermissionVO();
            BeanUtils.copyProperties(dto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100007);
    }

    @ApiOperation(value = "查询权限列表", notes = "分页查询权限列表（按创建时间倒序）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "权限类型：1-菜单，2-按钮，3-接口", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "status", value = "权限状态：0-禁用，1-启用", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/list")
    public Result<Page<SysPermissionVO>> list(
            Integer type,
            Integer status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Page<SysPermissionDTO> page = new Page<>(pageNum, pageSize);
        Wrapper<SysPermissionDTO> wrapper = new EntityWrapper<>();

        if (type != null) {
            wrapper.eq("type", type);
        }
        if (status != null) {
            wrapper.eq("status", status);
        }
        wrapper.orderBy("create_time", false);

        Page<SysPermissionDTO> dtoPage = sysPermissionService.selectPage(page, wrapper);
        Page<SysPermissionVO> voPage = new Page<>(dtoPage.getCurrent(), dtoPage.getSize());
        voPage.setTotal(dtoPage.getTotal());

        List<SysPermissionVO> voList = dtoPage.getRecords().stream().map(dto -> {
            SysPermissionVO vo = new SysPermissionVO();
            BeanUtils.copyProperties(dto, vo);
            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return new Result<>(voPage);
    }

    @ApiOperation(value = "查询权限详情", notes = "根据ID查询权限详情")
    @ApiImplicitParam(name = "id", value = "权限ID", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/get/{id}")
    public Result<SysPermissionVO> get(@PathVariable Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysPermissionDTO dto = sysPermissionService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        SysPermissionVO vo = new SysPermissionVO();
        BeanUtils.copyProperties(dto, vo);
        return new Result<>(vo);
    }

    @ApiOperation(value = "更新权限", notes = "根据ID更新权限信息（返回更新后完整数据）")
    @ApiImplicitParam(name = "id", value = "权限ID", required = true, paramType = "path", dataType = "Long")
    @PutMapping("/update/{id}")
    public Result<SysPermissionVO> update(
            @PathVariable Long id,
            @RequestBody SysPermissionSaveBO saveBO) {

        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysPermissionDTO existingDto = sysPermissionService.selectById(id);
        if (existingDto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        SysPermissionDTO updateDto = new SysPermissionDTO();
        BeanUtils.copyProperties(saveBO, updateDto);
        updateDto.setId(id);
        updateDto.setRevision(existingDto.getRevision());

        boolean success = sysPermissionService.updateById(updateDto);
        if (success) {
            SysPermissionDTO updatedDto = sysPermissionService.selectById(id);
            SysPermissionVO vo = new SysPermissionVO();
            BeanUtils.copyProperties(updatedDto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100008);
    }

    @ApiOperation(value = "删除权限", notes = "根据ID删除权限")
    @ApiImplicitParam(name = "id", value = "权限ID", required = true, paramType = "path", dataType = "Long")
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        boolean success = sysPermissionService.deleteById(id);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }

    @ApiOperation(value = "切换权限状态", notes = "根据ID切换权限状态（返回更新后数据）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限ID", required = true, paramType = "path", dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "状态：0-禁用，1-启用", required = true, paramType = "query", dataType = "Integer")
    })
    @PutMapping("/changeStatus/{id}")
    public Result<SysPermissionVO> changeStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {

        if (status != 0 && status != 1) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "状态值只能是0或1");
        }

        SysPermissionDTO dto = sysPermissionService.selectById(id);
        if (dto == null) {
            return new Result<>(CodeEnum.FAIL_100010);
        }

        dto.setStatus(status);
        dto.setRevision(dto.getRevision());
        boolean success = sysPermissionService.updateById(dto);
        if (success) {
            SysPermissionDTO updatedDto = sysPermissionService.selectById(id);
            SysPermissionVO vo = new SysPermissionVO();
            BeanUtils.copyProperties(updatedDto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100008);
    }
}